<?php

namespace app\index\service;

use app\common\model\CashTransfer;
use app\common\model\Trade;
use app\index\dao\TradeDao;
use app\index\model\UM as UM;
use app\index\service\payments\AccountPaymentService;
use think\exception\ValidateException;
use think\facade\Config;
use think\facade\Request;

/**
 * 提现订单
 * Class TradeCashService
 * @package app\index\service
 */
class TradeCashService implements TradableInterface
{
    // dao
    private TradeDao $tradeDao;

    public function __construct(TradeDao $tradeDao)
    {
        $this->tradeDao = $tradeDao;
    }

    /**
     * 提现订单-保存
     * @param UM $user
     * @param CashTransfer $cashTransfer
     * @return Trade
     */
    public function add(UM $user, CashTransfer $cashTransfer): Trade
    {
        // 补齐参数，创建Trade
        $tradeType = TRADE_CASH;
        $tradeConfig = Config::get("trade.trades.$tradeType", []);
        $tradeTypeClass = $tradeConfig['className'] ?? '';
        $memberId = $user->id;

        // 渠道链路
        ['pf' => $pf, 'chain' => $chain, 'promotionGroupId' => $promotionGroupId] = getChainParams();

        // 检查用户的余额账户是否可用
        if (!$this->getAccountPaymentService()->isEnableTransfer($memberId)) {
            throw new ValidateException('您的余额账户暂时不可用，请联系管理员');
        }

        $describe = $tradeConfig['name'] . $cashTransfer->total . '元';

        // 暂时没说优惠卷
        $showMoney = $cashTransfer->amount;
        $totalMoney = $cashTransfer->amount;
        $payMoney = $totalMoney;

        if ($payMoney < 0.01) {
            throw new ValidateException('订单价格应该大于0');
        }

        // 查询余额是否足够，不足直接说余额不足，请充值后操作
        $balance = $this->getAccountPaymentService()->getBalance($memberId);
        if($balance < $payMoney){
            throw new ValidateException('您的余额不足，请充值后继续操作');
        }

        $tradeParams = [
            // 余额支付
            'payMethod' => PAYMENT_ACCOUNT,
            'payStatus' => Trade::UNPAID,
            'memberId' => $memberId,
            'orderNoPre' => 'CA',
            'describe' => $describe,
            'tradeType' => $tradeType,
            'tradeTypeClass' => $tradeTypeClass,
            'cashTransferId' => $cashTransfer->id,
            'showMoney' => $showMoney,
            'totalMoney' => $totalMoney,
            'payMoney' => $payMoney,
            'payExpTime' => time() + 3600,
            'settleStatus' => Trade::NOTSETTLE,
            'pf' => $pf,
            'chain' => $chain,
            'promotionGroupId' => $promotionGroupId,
            'attach' => [
                'attach' => '',
            ],
        ];

        $record = $this->tradeDao->insertTrade($tradeParams);

        // 触发订单创建事件
        event('TradeCreated', $record);

        return $record;
    }

    // 完成订单
    public function completionTrade(Trade $trade)
    {

        // 设置服务开始和完成时间
        $time = time();
        $trade->startTime = $time;
        $trade->save();

        //查询提现申请，设置为已付款
        $cashTransfer = CashTransfer::where('id', $trade->cashTransferId)->find();
        if (!$cashTransfer) {
            // TODO 记录错误
            return;
        }

        // 保存已支付状态
        $cashTransfer->status = 1;
        $cashTransfer->save();

        // 如果审核已通过
        if ($cashTransfer->checkStatus == 1) {

            // 插入转账申请
            $this->getCashService()->createTransfer($cashTransfer);
        }

        // 触发订单完成事件
        event('TradeEnded', $trade);

    }

    // 完成退款
    public function completionRefundTrade(Trade $trade)
    {
        throw new ValidateException('退款订单不能退款');

        return;
    }

    public function canceledTrade(Trade $trade)
    {
        return;
    }
    private function getAccountPaymentService(): AccountPaymentService
    {
        return app(AccountPaymentService::class);
    }

    private function getCashService(): CashService
    {
        return app(CashService::class);
    }
}
